using UnityEngine;
using System.Collections.Generic;

public class BuildTimeManager : MonoBehaviour
{
	private class SpecialSpot
	{
		public float Multiplier;
		public float AliveUntil;
		public GameObject Light;
	}

	private static List<SpecialSpot> _specialSpots = new List<SpecialSpot>();
	private const float LIFETIME = 10;
	private const int SPOTCOUNT = 4;
	private const float SPOTSIZE = Balance.SPHERE_RADIUS;

	private void CreateSpecialSpot(Vector3 position)
	{
		var spot = new SpecialSpot()
		{
			Multiplier = Random.value,
			AliveUntil = Time.time + LIFETIME,
			Light = new GameObject("tmp.BuildTimeModifier")
		};
		
		spot.Light.transform.position = position;
		while (true)
		{
			float angle;
			Vector3 axis;
			Random.rotation.ToAngleAxis(out angle, out axis);
			spot.Light.transform.RotateAround(Vector3.zero, axis, angle);
			bool hasCloseNeighbors = false;
			foreach(var s in _specialSpots)
				hasCloseNeighbors |= (spot.Light.transform.position - s.Light.transform.position).magnitude < Balance.SPHERE_RADIUS;
			if (!hasCloseNeighbors)
				break;
		}
		spot.Light.AddComponent(typeof(Light));
		spot.Light.light.type = LightType.Point;
		spot.Light.light.color = new Color(1, 0.5f, 0.5f);
		spot.Light.light.intensity = 5;

		_specialSpots.Add(spot);
	}

	private void DestroySpecialSpot(SpecialSpot specialSpot)
	{
		_specialSpots.Remove(specialSpot);
		Destroy(specialSpot.Light.light);
		Destroy(specialSpot.Light);
	}

	void Start ()
	{
		
	}
	
	// Update is called once per frame
	void Update()
	{
		for (int i = _specialSpots.Count; --i >= 0; )
			if (Time.time > _specialSpots[i].AliveUntil)
				DestroySpecialSpot(_specialSpots[i]);

		if (_specialSpots.Count < SPOTCOUNT)
			CreateSpecialSpot(new Vector3(0, Balance.SPHERE_RADIUS + Balance.SPHERE_RADIUS * 0.15f, 0));

		foreach (var spot in _specialSpots)
		{
			float remainingTime = spot.AliveUntil - Time.time;
			spot.Light.light.range = SPOTSIZE / 2 * Mathf.Min(1, remainingTime / 2);
		}
	}

	public static float GetMultiplier(Vector3 position)
	{
		float res = 0;
		foreach (var spot in _specialSpots)
			res += Mathf.Clamp((SPOTSIZE - (spot.Light.transform.position - position).magnitude) / SPOTSIZE, 0, 1);
		return res;
	}
}
